import { observable, action, autorun, toJS } from 'mobx';
import { WeaLocaleProvider } from 'ecCom';
import { WeaForm, WeaTableNew } from 'comsMobx'
import { message, Button, Modal } from "antd";
import * as Apis from '../../apis/info';
import { ListStore } from '../listStore';
import { specialDialogStore } from '../dialog/specialDialogStore';
import { rewardDialogStore } from '../dialog/rewardDialogStore';
import { Text } from '../../components/util/text';
const text = new Text();

const { TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
export default class handleListStore extends ListStore {

	@observable specialDialogStore = new specialDialogStore(this);
	@observable rewardDialogStore = new rewardDialogStore(this);

	@observable responseData = {};
	@observable title = "";
	@observable dialogTitle = "";   //弹出框title
	@observable status = {
		loading: false,
		visible: false,  //筛选，弹出框dialog
		quickVisible: false,  // 快捷筛选弹出框dialog
		scoreVisible: false,   //历史分数弹出框
		jTypeVisible: false,   //新建期刊弹出框
		shareVisible: false    //已发布期刊中授权弹出框
	}
	@observable form = new WeaForm();    //筛选弹出框表单
	@observable condition = [];          //筛选弹出框condition
	@observable siftTableStore = new TableStore();      //筛选，特殊采用列表store
	@observable scoreTableStore = new TableStore();      //历史分数列表store
	//@observable periodsTableStore = new TableStore();    //历史期数tableStore
	@observable jTypeForm = new WeaForm();      //选择排版弹出框form
	@observable jTpeCondition = new WeaForm();  //选择排版弹出框condition

	@observable selectedData = [];
	@observable isRight = false;        //判断是否有权限
	@observable loadingSpin = true;     //全局loading

	@observable quickSiftForm = new WeaForm();      //快捷筛选弹出框form
	@observable quickSiftCondition = new WeaForm();  //快捷筛选弹出框condition
	@observable dataSource = [];
	@observable columns = [];

	type = "";               //类型判断，waitHandle,usedInfo,waitEdit,waitPublish,published
	selectTabKey = "";
	@observable tabs = [];          //regTop展示页签
	ids = "";        //加分操作时选择的记录
	jsonList = [];        //快捷加分按钮的json

	constructor(props) {
		super(props);
	}

	setState = (params = {}) => {
		Object.keys(params).forEach(o => {
			this.status[o] = params[o];
		})
		return this;
	}

	//得到处理信息list
	@action
	getInfoHandleList = (params = {}) => {
		//this.tabs = [];
		//第一次从url中获取type，waitHandle(待处理),usedInfo(已采用),waitEdit(待编),publishedInfoSifting(已发布待编),waitPublish(待发布期刊)，published(已发布期刊)
		if (typeof (params.type) != 'undefined') {
			this.type = params.type;
		}
		this.status.loading = true;
		let newParams = { 'pathId': this.selectTabKey, type: this.type };
		//根据type访问不同的接口
		//this.loadingSpin = true;
		this.searchForm = new WeaForm();
		this.searchCondition = [];
		if (this.type == 'waitEdit' || this.type == 'publishedInfoSifting') {
			Apis.getInfoSiftingList(newParams).then(data => {
				if (data.api_status == '1') {
					this.loadingSpin = false;
					this.isRight = data.isRight;
					if (!this.isRight) {
						return;
					}
					this.getListData(data);
				} else {
					message.error(data.api_errormsg);
				}
			});
		} else if (this.type == 'waitHandle' || this.type == 'usedInfo') {
			Apis.getInfoHandleList(newParams).then(data => {
				if (data.api_status == '1') {
					this.loadingSpin = false;
					this.isRight = data.isRight;
					if (!this.isRight) {
						return;
					}
					this.getListData(data);
				} else {
					message.error(data.api_errormsg);
				}
			})
		} else {
			Apis.getInfoJournalList(newParams).then(data => {
				if (data.api_status == '1') {
					this.loadingSpin = false;
					this.isRight = data.isRight;
					if (!this.isRight) {
						return;
					}
					this.getListData(data);
				} else {
					message.error(data.api_errormsg);
				}

			})
		}
	}

	getListData = (data = {}) => {
		if (this.tabs.length == 0) {
			// if (data.pathList.length > 1) {
			//     this.tabs.push({ key: 'all', title: text.ALLPATH });
			// } else {
			//    this.selectTabKey = data.pathList[0].id;
			// }
			this.tableStore = new TableStore();
			this.changeTab(data.pathList[0].id);
			data.pathList.map(m => {
				this.tabs.push({ key: m.id, title: m.name });
			});
			return;
		}
		this.title = data.title;
		this.tableStore.getDatas(data.sessionkey, 1);
		this.responseData = { rightMenus: data.rightMenus };
		this.jsonList = data.jsonList;
		// this.jsonList = [
		//     {
		//         rewardId: '1',
		//         showInView: '',
		//         showInList: '1',
		//         showName: '直接加分',
		//         rewardType: '0'
		//     }, {
		//         rewardId: '2',
		//         showInView: '',
		//         showInList: '1',
		//         showName: '选择刊型',
		//         rewardType: '1'
		//     }
		// ];
		this.searchCondition = data.infoConditionGroup;
		this.searchForm && !this.searchForm.isFormInit && this.searchForm.initFormFields(data.infoConditionGroup);
		this.status.loading = false;
	}

	@action
	doSearch = (params = {}) => {
		this.status.loading = true;
		//获取表单的参数值
		const searchParamsAd = this.searchForm.getFormParams();
		const newParams = { ...searchParamsAd, 'type': this.type, 'pathId': this.selectTabKey };
		if (this.type == 'waitEdit' || this.type == 'publishedInfoSifting') {
			Apis.getInfoSiftingList(newParams).then(data => {
				this.doSearchResult(data);
			});
		} else if (this.type == 'waitHandle' || this.type == 'usedInfo') {
			Apis.getInfoHandleList(newParams).then(data => {
				this.doSearchResult(data);
			})
		} else {
			Apis.getInfoJournalList(newParams).then(data => {
				this.doSearchResult(data);
			})
		}
	}

	doSearchResult = (data) => {
		this.tableStore = new TableStore();
		this.tableStore.getDatas(data.sessionkey, 1);
		this.status.loading = false;
	}

	//初始化筛选弹出框condition
	@action
	getFilterDialogCondition = (params = {}) => {
		Apis.getFilterDialogCondition(params).then(data => {
			if (data.api_status == '1') {
                if (!data.isRight) {
                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                    return;
                }
                this.status.visible = true;
				this.condition = data.infoConditionGroup;
				this.form = new WeaForm();
				this.form && !this.form.isFormInit && this.form.initFormFields(this.condition);
				this.siftTableStore.getDatas(data.sessionkey, 1)
			} else {
				message.error(data.api_errormsg);
			}

		});
	}

	//快捷筛选弹出框condition
	@action
	getQuickFilterDialogCondition = (params = {}) => {
		Apis.getQuickFilterDialogCondition(params).then(data => {
			if (data.api_status == '1') {
                if (!data.isRight) {
                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                    return;
                }
                this.status.quickVisible = true;
				this.quickSiftCondition = data.infoConditionGroup;
				this.quickSiftForm = new WeaForm();
				this.quickSiftForm && !this.quickSiftForm.isFormInit && this.quickSiftForm.initFormFields(this.quickSiftCondition);
			} else {
				message.error(data.api_errormsg);
			}

		});
	}

	// formChange = () => {
	//     let formParams = this.quickSiftForm.getFormParams();
	//     let newParams = { 'j_type': formParams.j_type };
	//     Apis.getQuickJournalList(newParams).then(data => {
	//         if (data.api_status == '1') {
	//             this.dataSource = data.dataSource;
	//             this.columns = data.columns;
	//         } else {
	//             message.error(data.api_errormsg);
	//         }

	//     })
	// }
	//快捷筛选查询期刊
	@action
	searchJournal = (v) => {
		let formParams = this.quickSiftForm.getFormParams();
		if (formParams.j_type == '') {
			message.error("请选择刊型！");
			this.dataSource = [];
			return;
		}
		let newParams = { 'j_type': formParams.j_type, name: v || '' };
		Apis.getQuickJournalList(newParams).then(data => {
			if (data.api_status == '1') {
				this.dataSource = data.dataSource;
				this.columns = data.columns;
			} else {
				message.error(data.api_errormsg);
			}

		})
	}
	//保存快捷筛选
	@action
	saveQuickSift = (params = {}) => {
		//   let formParams = this.quickSiftForm.getFormParams();
		//   let selectedRowKeys = this.tableStore.selectedRowKeys;
		//   let newParams = {...formParams,ids:selectedRowKeys.join(",")};
		//   let _this = this;
		//   this.quickSiftForm.validateForm().then(f => {
		//     if (f.isValid) {
		//         Apis.getQuickJournalList(newParams).then(data => {
		//           if (data.api_status == '1') {
		//               if (data.result == true) {
		//                   message.error('该期刊已成文，无法筛选至此期刊');
		//               } else {
		//                   Apis.saveQuickFilter(newParams).then(data => {
		//                     if (data.api_status == '1') {
		//                       if(typeof(data.msg) != 'undefined') {
		//                         message.error(data.msg);
		//                         return ;
		//                       }
		//                         Modal.confirm({
		//                           content: '快捷筛选成功，是否跳转至排版界面?',
		//                           onOk() {
		//                               _this.status.quickVisible = false;
		//                               window._table.reLoad();
		//                               openFullWindowForXtable('/spa/info/static/index.html#/main/info/composing?id=' + data.journalId + "&type=show&isSpecialReport=false");
		//                           },
		//                           onCancel() { },
		//                       });
		//                     } else {
		//                         message.error(data.api_errormsg);
		//                     }
		//                 });
		//               }
		//           } else {
		//               message.error(data.api_errormsg);
		//           }

		//         });
		//     } else {
		//         f.showErrors();
		//     }
		// });
		let formParams = this.quickSiftForm.getFormParams();
		let selectedRowKeys = this.tableStore.selectedRowKeys;
		let newParams = { ...params, ...formParams, ids: selectedRowKeys.join(",") };
		let _this = this;
		Apis.checkJournalType(newParams).then(data => {
			if (data.api_status == '1') {
				if (data.flag == true) {
					message.error('该刊型已经被引用');
				} else {
					this.quickSiftForm.validateForm().then(f => {
						if (f.isValid) {
							Apis.saveQuickFilter(newParams).then(data => {
								if (data.api_status == '1') {
                                    if (!data.isRight) {
                                        message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                        return;
                                    }
									Modal.confirm({
										content: '快捷筛选成功，是否跳转至排版界面?',
										onOk() {
											_this.status.quickVisible = false;
											window._table.reLoad();
											setTimeout(() => {
												openFullWindowForXtable('/spa/info/static/index.html#/main/info/composing?id=' + data.journalId + "&type=show&isSpecialReport=false&isQuickSift=true");
											}, 300);

										},
										onCancel() {
											_this.status.quickVisible = false;
											window._table.reLoad();
										},
									});
								} else {
									message.error(data.api_errormsg);
								}
							});
						} else {
							this.quickSiftForm.showError('j_type', '刊型栏目未填写完整');
						}
					});
				}
			} else {
				message.error(data.api_errormsg);
			}
		});

	}

	//获取历史分数table
	@action
	getRewardListByInfoSiftId = (params = {}) => {
		this.ids = params.id;
		Apis.getRewardListByInfoSiftId(params).then(data => {
			if (data.api_status == '1') {
				this.scoreTableStore.getDatas(data.sessionkey, 1)
			} else {
				message.error(data.api_errormsg);
			}

		});
	}

	//获取排版入口弹出框condition
	@action
	getJtypeCondition = (paarms = {}) => {
		let newParams = { 'type': 'specialUse', 'pathId': this.selectTabKey };
		Apis.getSpecialHandleCondition(newParams).then(data => {
			if (data.api_status == '1') {
                if (!data.isRight) {
                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                    return;
                }
                this.setState({ jTypeVisible: true });
				this.jTpeCondition = data.infoConditionGroup;
				this.jTypeForm && !this.jTypeForm.isFormInit && this.jTypeForm.initFormFields(this.jTpeCondition);
			} else {
				message.error(data.api_errormsg);
			}

		});
	}

	//选择刊型进行排版
	enterComposing = (params = {}) => {
		let formParams = this.jTypeForm.getFormParams();
		this.jTypeForm.validateForm().then(c => {
			if (c.isValid) {
				this.setState({ jTypeVisible: false });
				//openFullWindowForXtable('/#/info/composing?j_type=' + formParams.j_type);
				openFullWindowForXtable('/spa/info/static/index.html#/main/info/composing?j_type=' + formParams.j_type);
			} else {
				c.showErrors();
			}
		})

	}

	//删除历史加分记录
	@action
	delScore = (params = {}) => {
		let selectedRowKeys = this.scoreTableStore.selectedRowKeys;
		if (selectedRowKeys.length == 0) {
			message.warn(text.CHOOSERECORD);
			return;
		}
		let _this = this;
		Modal.confirm({
			title: text.SYSTEMTIP,
			content: text.SUREDELETE,
			onOk() {
				let newParams = { 'ids': selectedRowKeys.join(",") };
				Apis.deleteAddScore(newParams).then(data => {
					if (data.api_status == '1') {
                        if (!data.isRight) {
                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                            return;
                        }
						message.success(text.DELSUCCESS);
						//刷新得分历史和已发布的待编信息table
						_this.scoreTableStore.getDatas(_this.scoreTableStore.dataKey, _this.scoreTableStore.current, _this.scoreTableStore.pageSize, _this.scoreTableStore.sortParams);
						_this.tableStore.getDatas(_this.tableStore.dataKey, _this.tableStore.current, _this.tableStore.pageSize, _this.tableStore.sortParams);
					} else {
						message.error(data.api_errormsg);
					}
				});
			}
		});
	}

    /**
     * 向后台传递参数，触发保存刊型和栏目动作
     */
	@action
	saveJtypeAndJcolumn = (params) => {
		let formParams = this.form.getFormParams();
		let selectedRowKeys = toJS(this.tableStore.selectedRowKeys);
		params = { ...formParams, ids: selectedRowKeys.join(',') };
		this.form.validateForm().then(c => {
			if (c.isValid) {
				if (formParams.cascaderValue && formParams.cascaderValue[1]) {
					Apis.saveJtypeAndJcolumn(params).then(data => {
                        if (!data.isRight) {
                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                            return;
                        }
						window._table.reLoad();
						this.setState({ visible: false });
					});
				} else {
					message.warn(text.NODATA);
				}
			} else {
				c.showErrors();
			}
		})
	}

    /**
     * 保存期刊共享权限
     */
	@action
	addShare = (params) => {
		//添加期刊的非默认共享查看权限   datatype为0   opttype为0
		let newParams = { ...params, pathId: this.selectTabKey, datatype: 0, opttype: 0, ids: this.tableStore.selectedRowKeys.join(',') };
		Apis.addShare(newParams).then(data => {
			if (data.api_status == '1') {
                if (!data.isRight) {
                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                    return;
                }
				message.success('添加权限成功');
			} else {
				message.error(data.api_errormsg);
			}
		});
	}

	getRightMenu = () => {
		const { rightMenus } = this.responseData;
		let btnArr = [];
		rightMenus && rightMenus.length > 0 && rightMenus.map(m => {
			btnArr.push({
				key: m.type,
				icon: <i className={m.menuIcon} />,
				content: m.menuName,
				onClick: key => {
					this.buttonClick(key);
				},
				disabled: this.tableStore.selectedRowKeys.length === 0 && (m.type == 'BTN_FILTER' || m.type == 'BTN_COPPOSING' || m.type == 'BTN_SPECIAL_USE' || m.type == 'BTN_SPECIAL_REPORT' || m.type == 'BTN_ADD_SCORE' || m.type == 'BTN_QUICK_FILTER' || m.type == 'BTN_AUTHORIZATION')
			})
		});
		return btnArr;
	}

	//设置选中按钮
	@action
	changeTab = (key) => {
		this.selectTabKey = key;
		this.getInfoHandleList();
	}

    /**
   * 上方按钮
   */
	getTopButton = () => {
		const { rightMenus } = this.responseData;
		let selectedRowKeys = toJS(this.tableStore.selectedRowKeys);
		let btnArr = [];
		this.jsonList && this.jsonList.length > 0 && this.jsonList.map((m,index) => {
			if (m.showInList == '1') {
				btnArr.push(
					<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@94uhwp@${index}`} style={{ marginLeft: "10px" }} type={"primary"}
						disabled={this.tableStore.selectedRowKeys.length === 0}
						onClick={() => {
							let _this = this;
							Modal.confirm({
								title: text.SYSTEMTIP,
								content: text.SUREADDSCORE,
								onOk() {
									if (m.rewardType == '0') {
										let tableJson = [{ "id": m.rewardId, "type": 0 }]
										let params = { 'tableJson': JSON.stringify(tableJson), ids: selectedRowKeys.join(',') };
										Apis.saveAddScore(params).then(result => {
											if (result.api_status == '1') {
                                                if (!result.isRight) {
                                                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                                    return;
                                                }
												if (typeof (result.msg) != 'undefined') {
													message.error(result.msg);
													return;
												}
												message.success(text.SAVESUCCESS);
												let table = _this.tableStore;
												table.getDatas(table.dataKey, table.current, table.pageSize, table.sortParams);
											} else {
												message.error(result.api_errormsg);
											}
										})
									}
									if (m.rewardType == '1' || m.rewardType == '2') {
										_this.rewardDialogStore.getRewardList({ 'rewardId': m.rewardId, 'type': '4' });
										_this.ids = selectedRowKeys.join(',');
										//_this.rewardDialogStore.setState({ visible: true });
									}
								}
							});
						}}>
						{m.showName}
					</Button>
				);
			}
		});
		rightMenus && rightMenus.length > 0 && rightMenus.map((m,index) => {
			btnArr.push(
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@c21yzk@${index}`} style={{ marginLeft: "10px" }} type={"primary"}
					disabled={(m.type == 'BTN_FILTER' || m.type == 'BTN_COPPOSING' || m.type == 'BTN_SPECIAL_USE' || m.type == 'BTN_SPECIAL_REPORT' || m.type == 'BTN_ADD_SCORE' || m.type == 'BTN_QUICK_FILTER' || m.type == 'BTN_AUTHORIZATION')
						&& this.tableStore.selectedRowKeys.length === 0}
					onClick={() => {
						this.buttonClick(m.type);
					}}>
					{m.menuName}
				</Button>
			);

		});
		return btnArr;
	}

	buttonClick(key) {
		if (key == "BTN_FILTER") {                      //筛选
			let selectedRowKeys = toJS(this.tableStore.selectedRowKeys);
			let flag = true;        //不能筛选专报的信息
			for (let i = 0; i < this.selectedData.length; i++) {
				if (this.selectedData[i].reportType == '1') {
					flag = false;
					break;
				}
			}
			if (flag) {
				this.getFilterDialogCondition({ ids: selectedRowKeys.join(','), type: 'sift' });
			} else {
				message.warn(text.TIP3);
			}
		}
		if (key == "BTN_REPORT_BYOTHERS") {             //代报
			//openFullWindowForXtable('/#/info/infoReport?by=assistReport&pathId=' + this.selectTabKey);
			openFullWindowForXtable('/spa/info/static/index.html#/main/info/infoReport?by=assistReport&pathId=' + this.selectTabKey);
		}
		if (key == 'BTN_COPPOSING') {                    //排版
			let curJournaltype = "";
			let flag = true;       //是否选择同一种刊型的标识
			let datas = this.tableStore.datas;
			let selectedRowKeys = this.tableStore.selectedRowKeys;
			//判断是否选择的同一种刊型的待编信息进行排版
			// if (selectedRowKeys.length > 1) {
			//     for (let i = 0; i < datas.length; i++) {
			//         if (!flag) {
			//             break;
			//         }
			//         for (let j = 0; j < selectedRowKeys.length; j++) {
			//             if (curJournaltype == '' && datas[i].id == selectedRowKeys[j]) {
			//                 curJournaltype = datas[i].j_type;
			//                 break;
			//             }
			//             if (curJournaltype != '' && datas[i].id == selectedRowKeys[j] && datas[i].j_type != curJournaltype) {
			//                 flag = false;
			//                 break;
			//             }
			//         }
			//     }
			// }
			if (selectedRowKeys.length > 1) {
				for (let i = 0; i < this.selectedData.length; i++) {
					if (i == 0) {
						curJournaltype = this.selectedData[i].j_type;
						continue;
					}
					if (i != 0 && curJournaltype != this.selectedData[i].j_type) {
						flag = false;
						break;
					}
				}
			}
			if (flag) {
				//openFullWindowForXtable('/#/info/composing?ids=' + this.tableStore.selectedRowKeys.join(','));
				openFullWindowForXtable('/spa/info/static/index.html#/main/info/composing?ids=' + this.tableStore.selectedRowKeys.join(','));
			} else {
				message.warn(text.TIP4);
			}
		}
		if (key == "BTN_SPECIAL_USE") {                      //特殊采用
			let selectedRowKeys = this.tableStore.selectedRowKeys;
			this.specialDialogStore.getSpecialHandleCondition({ ids: selectedRowKeys.join(','), type: 'specialUse', by: 'list' });
			//this.specialDialogStore.setState({ visible: true });
		}
		if (key == 'BTN_SPECIAL_REPORT') {                    //专报
			let selectedRowKeys = this.tableStore.selectedRowKeys;
			if (selectedRowKeys.length != 1 || this.selectedData[0].reportType != '1') {
				message.warn(text.TIP5);
				return;
			}
			this.specialDialogStore.getSpecialHandleCondition({ ids: selectedRowKeys.join(','), type: 'specialReport', by: 'list' });
			//this.specialDialogStore.setState({ visible: true });
		}
		if (key == 'BTN_ADD_SCORE') {         //加分
			let selectedRowKeys = this.tableStore.selectedRowKeys;
			this.ids = selectedRowKeys.join(',');
			this.rewardDialogStore.getRewardList({ 'pathId': this.selectTabKey, 'type': '1' });
			//this.rewardDialogStore.setState({ visible: true });
		}
		if (key == 'BTN_CREATE') {          //新建按钮，选择刊型进入排版入口
			this.getJtypeCondition();
			
		}
		if (key == 'BTN_QUICK_FILTER') {    //快捷筛选
			let selectedRowKeys = this.tableStore.selectedRowKeys;
			let flag = true;
			for (let i = 0; i < this.selectedData.length; i++) {
				if (this.selectedData[i].reportType == '1') {
					message.warn('专报信息无法进行快捷筛选');
					flag = false;
					break;
				}
			}
			if (flag) {
				this.columns = [];
				this.dataSource = [];
				//this.status.quickVisible = true;
				this.getQuickFilterDialogCondition({ ids: selectedRowKeys.join(',') });
			}
		}
		if (key == 'BTN_AUTHORIZATION') {       //授权
			this.status.shareVisible = true;
		}
	}

}